package base.thread_demo.demo17;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Random;
import java.util.concurrent.*;

/**
 * 本案例演示两个内容:
 *
 * 1.获取线程池中单线程执行结果
 *
 * 2.获取线程池所有线程任务执行结果(谁先任务完成就返回谁的结果)
 */
public class ThreadPoolWaitingTaskReturn {
    private static Logger logger = LoggerFactory.getLogger(ThreadPoolWaitingTaskReturn.class);

    public static void main(String[] args) {
//        case1();
        case2();
    }

    // 获取线程池中单个线程执行结果
    public static void case1(){
        ExecutorService executor = Executors.newSingleThreadExecutor();// 单个线程的线程池
        // 这里要拿到线程执行结果,因此 new 的是 Callable 而不是 Runnable
        Future<String> future = executor.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(5000);
                return "SUCCESS";
            }
        });
        logger.info("等待执行结果......");

        try {
            String result = future.get();
            logger.info("拿到结果：{}",result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        executor.shutdown();
        logger.info("阻塞式等待结果结束.");
    }


    // 将线程池中所有线程的执行结果拿回来
    public static void case2(){
        ExecutorService executor = Executors.newFixedThreadPool(10);
        ExecutorCompletionService<Integer> executorCompletionService = new ExecutorCompletionService<>(executor);
        // 往线程池中添加10个任务
        for (int i = 0; i < 10; i++) {
            final int seq = i;
            executorCompletionService.submit(new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    // 每个任务开始休眠5s
                    Thread.sleep(new Random().nextInt(5000));
                    return seq;
                }
            });
        }
        //logger.info("-----等待获取结果-------");
        // 获取任务执行结果
        for (int i = 0; i < 10; i++) {
            try {
                Integer result = executorCompletionService.take().get();
                logger.info("获取线程任务结果:{}", result);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        executor.shutdown();
        logger.info("-----结果获取结束-------");
    }
}
